import { useEffect, useRef, useState } from 'react'
import { useDispatch } from 'react-redux'
import { addNotification } from '../store/slices/notificationSlice'
import io from 'socket.io-client'

export const useWebSocket = (url = 'ws://localhost:5000') => {
  const [isConnected, setIsConnected] = useState(false)
  const [lastMessage, setLastMessage] = useState(null)
  const socketRef = useRef(null)
  const dispatch = useDispatch()

  useEffect(() => {
    // 创建 WebSocket 连接
    socketRef.current = io(url, {
      transports: ['websocket'],
      autoConnect: true,
    })

    const socket = socketRef.current

    socket.on('connect', () => {
      setIsConnected(true)
      console.log('WebSocket 连接已建立')
    })

    socket.on('disconnect', () => {
      setIsConnected(false)
      console.log('WebSocket 连接已断开')
    })

    socket.on('notification', (data) => {
      dispatch(addNotification(data))
      setLastMessage(data)
    })

    socket.on('device_status', (data) => {
      setLastMessage({ type: 'device_status', data })
    })

    socket.on('energy_data', (data) => {
      setLastMessage({ type: 'energy_data', data })
    })

    socket.on('security_alert', (data) => {
      setLastMessage({ type: 'security_alert', data })
    })

    socket.on('parking_update', (data) => {
      setLastMessage({ type: 'parking_update', data })
    })

    socket.on('error', (error) => {
      console.error('WebSocket 错误:', error)
    })

    return () => {
      socket.disconnect()
    }
  }, [url, dispatch])

  const sendMessage = (event, data) => {
    if (socketRef.current && isConnected) {
      socketRef.current.emit(event, data)
    }
  }

  return {
    isConnected,
    lastMessage,
    sendMessage,
  }
}

export const useRealTimeData = (dataType) => {
  const [data, setData] = useState(null)
  const [loading, setLoading] = useState(true)
  const { lastMessage } = useWebSocket()

  useEffect(() => {
    if (lastMessage && lastMessage.type === dataType) {
      setData(lastMessage.data)
      setLoading(false)
    }
  }, [lastMessage, dataType])

  return { data, loading }
}